package com.liushuang.waiwaiim.model.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.liushuang.waiwaiim.model.bean.UserInfo;
import com.liushuang.waiwaiim.model.db.UserAccountDBHelper;

public class UserAccountDao {

    private UserAccountDBHelper mHelper;

    public UserAccountDao(Context context){
        mHelper = new UserAccountDBHelper(context);
    }

    //添加用户到数据库中
    public void addAccount(UserInfo userInfo){
        SQLiteDatabase db = mHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(UserAccountTable.COL_HXID, userInfo.getHxid());
        values.put(UserAccountTable.COL_NAME, userInfo.getName());
        values.put(UserAccountTable.COL_NICK, userInfo.getNick());
        values.put(UserAccountTable.COL_PHOTO, userInfo.getPhoto());
        db.replace(UserAccountTable.TABLE_NAME, null, values);

        db.close();
    }

    //根据环信id获取所有用户信息
    public UserInfo getAccountByHxId(String hxId){
        SQLiteDatabase db = mHelper.getReadableDatabase();

        //执行查询语句
        String sql = "select * from " + UserAccountTable.TABLE_NAME + " where " + UserAccountTable.COL_HXID + "=?";
        Cursor cursor = db.rawQuery(sql, new String[]{hxId});

        UserInfo userInfo = null;
        if (cursor != null){
            if (cursor.moveToFirst()){
                userInfo = new UserInfo();
                //封装对象
                userInfo.setHxid(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_HXID)));
                userInfo.setName(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_NAME)));
                userInfo.setNick(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_NICK)));
                userInfo.setPhoto(cursor.getString(cursor.getColumnIndex(UserAccountTable.COL_PHOTO)));
            }
        }
        //关闭资源
        cursor.close();
        db.close();
        //返回数据
        return userInfo;
    }

}
